package net.guerlab.ali.dayu;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 请求发送者
 * 
 * @author guer
 *
 */
public class Sender {

    private static final Logger LOGGER = LoggerFactory.getLogger(Sender.class);

    /**
     * 请求地址
     */
    public static final String SEND_URL = "https://ca.aliyuncs.com/gw/alidayu/sendSms";

    private static final ResponseHandler<String> RESPONSEHANDLER = new StringResponseHandler();

    /**
     * 发送请求
     * 
     * @param appliaction
     *            应用对象
     * @param msg
     *            消息对象
     * @return 回复内容对象
     * @throws DayuException
     *             当发送失败或者请求失败的时候抛出DayuException异常
     */
    public static final Result send(Appliaction appliaction, Msg msg) throws DayuException {
        if (appliaction == null) {
            throw new DayuException("Appliaction Object cann't be null");
        }

        if (msg == null) {
            throw new DayuException("Msg Object cann't be null");
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpUriRequest request = RequestBuilder.get(SEND_URL)
                .addHeader("X-Ca-Key", appliaction.getKey())
                .addHeader("X-Ca-Secret", appliaction.getSecret())
                .addParameter("rec_num", msg.getNum())
                .addParameter("sms_template_code", msg.getTemplateCode())
                .addParameter("sms_free_sign_name", msg.getSignName())
                .addParameter("sms_type", "normal")
                .addParameter("extend", msg.getExtend())
                .addParameter("sms_param", msg.getParam().toString()).build();

        try {
            String responseBody = httpClient.execute(request, RESPONSEHANDLER);

            LOGGER.info("get responseBody -> {}", responseBody);

            return Result.parse(responseBody);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new DayuException("Request error", e);
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                /**
                 * don't need todo something
                 */
            }
        }
    }
}
